<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/index.css"/>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/toastr.min.css"/>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/vue.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/axios.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/toastr.min.js"></script>
    <title>资源上传</title>
</head>
<body>

<jsp:include page="/WEB-INF/common/nav.jsp" />

<article>
    <!-- 网站主体 -->
    <div id="main">
        <section class="ct">
            <!-- 上传表单-->
            <div class="upload">
                <h1>上传资源<em>声明：请确保您上传的内容合法合规，涉及侵权内容将会被移除，详见<a>《爱下载资源共享规则》</a></em></h1>
                <form action="" method="post">

                    <p class="file">
                        <input type="file" name="resource" @change="upload">

                        <span class="t1" v-if="!uploaded">点击上传、文件小于1000MB（请不要上传存在侵权的资源哦！）</span>
                        <!-- 上传后的效果 -->
                        <span class="t2" v-if="uploaded">
                            <img :src="'${pageContext.request.contextPath}/static/images/' + fileExt + '.svg'" />
                            <b>{{resource.filename}}</b>
                            <progress :value="process" max="100" v-show="progress"></progress>
                            <a>重新上传</a>
                        </span>
                    </p>

                    <p>
                        <label><em>*</em>资源名称：</label>
                        <input class="upt" type="text" name="resourceName" v-model.trim="resource.filename" placeholder="请输入资源名" />
                        <em></em> <!-- 显示错误信息  -->
                    </p>

                    <p>
                        <label>资源描述：</label>
                        <textarea  class="area" v-model.trim="resource.description" placeholder="简要介绍一下资源内容"></textarea>
                    </p>

                    <p>
                        <label><em>*</em>关键词：</label>
                        <span class="key-tag">
                            <a class="key">
                                <span v-for="(keyword, index) in resource.keywords" :key="keyword" @click="resource.keywords.splice(index, 1)">{{keyword}}</span>
                                <!-- 单击添加标签后、产生的效果 -->
                                <input type="text" v-if="addKeyword" @keydown.enter="handlerKeyword" @keydown.esc="addKeyword = false"/>
                            </a>
                            <span class="key-tag-msg" v-if="resource.keywords.length < 5">
                                <button type="button" class="keywords add" @click="addKeyword = true">添加标签</button>
                                <i class="lb">按回车键创建标签, ESC取消</i>
                            </span>
                        </span>
                        <span class="source-tag-msg">最多添加5个标签，每个标签不超过16个字</span>
                    </p>

                    <div class="source-type-div">
                        <p>
                            <label><em>*</em>所属分类：</label>
                            <input class="upt source-type source-type-down" type="text" name="resource_type"
                                   :value="resourceText"
                                   readonly placeholder="请选择" />
                        </p>
                        <div class="source-type-list">
                            <select size="99999" class="one" @change="handlerResourceType" v-model="oneType">
                                <template v-for="(type, index) in resourceTypes">
                                    <option :value="type.id" v-if="type.pid == null">{{type.name}}</option>
                                </template>
                            </select>
                            <select class="two" size="99999" @change="handlerTwoType"  v-model="twoType">
                                <option v-for="(type, index) in twoTypes" :value="type.id">{{type.name}}</option>
                            </select>
                        </div>
                    </div>

                    <p>
                        <label><em>*</em>资源分：</label>
                        <select class="upt" id="sel" name="score" v-model="resource.score">
                            <option selected="selected">0</option>
                            <option>1</option>
                            <option>2</option>
                            <option>3</option>
                            <option>4</option>
                            <option>5</option>
                        </select>
                    </p>

                    <p>
                        <label>验证码：</label>
                        <input id="code" class="upt captcha" type="text" name="code" v-model="resource.code"
                               placeholder="请输入验证码,如果看不清，点击验证码进行刷新"/>
                        <img class="captcha" @click="refreshCode" :src="captcha" />
                        <em></em>
                    </p>

                    <p><label class="btn"><a class="btn" @click="handlerSubmit">提交</a></label></p>
                </form>
            </div>
        </section>
    </div>
</article>

<jsp:include page="/WEB-INF/common/footer.jsp" />

<script>

    new Vue({
        el: "#main" ,
        data: {
            captcha: "${pageContext.request.contextPath}/captcha/code?w=140&h=40" , // 验证码地址
            uploaded: false, // 是否上传
            progress: false,
            addKeyword: false, //添加关键字
            ext: '',
            process: 0 ,
            oneType: '',
            twoType: '',
            resourceTypes: [] , // 所有的资源分类信息
            resourceText: '' ,
            twoTypes: [] , // 存放二级数据
            resource: {
                url: "" ,
                filename: '',
                description: "" ,
                score: 0 ,
                code: "" ,
                keywords: [] , // 用来存储关键字
                size: 0 ,
            }
        },
        created() {
            this.queryResourceTypes() ;
        },
        methods: {
            handlerSubmit: async function(event){
                // 1. 验证是否上传 了文件
                if (this.resource.url === "") {
                    toastr.error("请选择要上传的资源或者等待资源上传完成");
                    return ;
                }
                // 2. 验证资源名是否填充
                if (this.resource.filename === "") {
                    toastr.error("请输入上传的资源名称");
                    return ;
                }

                // 3. 判断关键字是否提供
                if (this.resource.keywords.length == 0) {
                    toastr.error("请至少提供一个关键字信息");
                    return ;
                }
                // 4. 判断 类型是否选择
                if (this.twoType == null || this.twoType === "") {
                    toastr.error("请选择资源所属分类信息");
                    return ;
                }
                // 5. 校验验证码
                if (this.resource.code === "") {
                    toastr.error("验证码必选提供");
                    return ;
                }
                // 6. 发送异步请求,校验检验码是否正确
               let ret = await axios.get("${pageContext.request.contextPath}/res/checkCode?code=" + this.resource.code) ;
               if (ret.data.success) {
                   // 封装请求表单参数
                   let params = {
                       resourceName: this.resource.filename ,
                       description: this.resource.description ,
                       resourceUrl: this.resource.url ,
                       keywords: this.resource.keywords.join("::"),
                       typeId: this.twoType ,
                       score: this.resource.score ,
                       code : this.resource.code ,
                       ext: this.ext,
                       size: this.resource.size
                   } ;
                   // 以表单格式发送请求
                   let ret =  await axios.post("${pageContext.request.contextPath}/res/add", params , {
                       headers: {
                           "content-type": "application/x-www-form-urlencoded"
                       }
                   }) ;
                   if (ret.data.success) {
                       // 如果资源保存成功,
                       toastr.success(ret.data.message) ;
                       // 清空数据
                       this.uploaded = false ;
                       this.resource.url = "" ;
                       this.resource.filename = "" ;
                       this.resource.description = "" ;
                       this.resource.score = 0 ;
                       this.resource.code = "" ;
                       this.resource.keywords = [] ;
                       this.resource.size = "" ;
                       this.resourceText = "" ;
                       this.twoType = "" ;
                       this.oneType = "" ;
                       this.refreshCode(); // 刷新验证码
                       return ;
                   }else{
                       toastr.error(ret.data.message);
                   }
               }else{
                   toastr.error(ret.data.message);
               }
            },
            handlerTwoType(event){
                // 获取 选中的一级类型 对应的 名字 和 二级类型对应的名字
               let one = this.resourceTypes.find(resource=> resource.id == this.oneType) ;
               let two = this.resourceTypes.find(resource=> resource.id == this.twoType) ;
               this.resourceText = one.name + "/" + two.name ;
               // document.querySelector(".source-type-list").style.display = "none" ;
            },
            handlerResourceType(event) {
                // 获取 下拉列表选中的元素
                let resId = event.target.value ;
                // 找到 该资源ID 对应的 二级分类
                this.twoTypes = this.resourceTypes.filter(res => res.pid == resId) ;
            },
            queryResourceTypes() {
                axios.get("${pageContext.request.contextPath}/res/types").then(ret=> {
                    if (ret.data.success) {
                        this.resourceTypes = ret.data.data ;
                    }
                })
            },
            handlerKeyword(event){
                // 获取到输入的关键字信息
                let key = event.target.value ;
                if (key.trim() === "") return ;
                // 如果输入了关键字, 判断关键字的长度
                if (key.trim().length > 16) {
                    toastr.error("关键字过长");
                    return ;
                }
                if (this.resource.keywords.includes(key.trim())) {
                    toastr.error("该关键字已经存在");
                    return ;
                }
                this.resource.keywords.push(key.trim()) ;
                // 关闭 输入框
                this.addKeyword = false ;

            },
            refreshCode(event) {
                let timestamp = new Date().getTime();
                this.captcha = "${pageContext.request.contextPath}/captcha/code?w=140&h=40&_=" + timestamp ;
            },
            upload(event) {
                this.process = 0 ; // 进度条从0开始
                this.progress = true ; // 打开进度条
                // 获取上传的资源信息
                let file = event.target.files[0];
                // 获取 上传文件的 名字
                let filename = file.name ;
                // 设置文件大小
                this.resource.size = file.size ;
                // 获取 后缀名 , 以 最后一个点 作为截取后缀的标识
                let index = filename.lastIndexOf(".") ;

                if (index >= 0) {
                    this.resource.filename = filename.substring(0, index);
                    this.ext = filename.substring(index + 1) ;
                }else{
                    this.resource.filename = filename ;
                    this.ext = "" ;
                }
                let playing = setInterval(() => {
                    this.process += 0.05 ;
                    if (this.process >= 99) {
                        clearInterval(playing);
                    }
                }, 20) ;

                this.uploaded = true ;
                // 发送异步请求,准备上传资源
                axios.postForm("${pageContext.request.contextPath}/res/upload" , {resource: file}).then(ret=> {
                    // 如果上传成功
                    if (ret.data.success) {
                        this.process = 100 ;
                        clearInterval(playing);
                        // 将上传的地址 存储起来
                        this.resource.url = ret.data.data ;
                        setTimeout(()=> {
                            this.progress = false;
                        } , 500);
                    }
                })
            }
        },
        computed: {
            fileExt() {
                let supportExts = ["doc" , "docx", "exe", "gif", "gz", "html", "md", "mp4" , "pdf", "png" , "ppt" , "pptx" , "rar" , "rmvb" , "txt" , "wps" , "xls" , "xlsx" , "zip", "7z", "avi" , "bmp"] ;
                if (supportExts.includes(this.ext)) {
                    return this.ext ;
                }
                return "unknow" ;
            }
        }
    })

    $(function(){

        $(".source-type").on("click", function(event){
            $(".source-type-list").show();
            event.stopPropagation();
        })
        $(document).on("keydown click", function(event){
            if (event.keyCode === 27 && event.type == 'keydown' ||
                (!$('.source-type-list').has(event.target).length && event.type == 'click')) {
                $(".source-type-list").hide();
            }
        })
    })

</script>

</body>

</html>